package com.coszero.utils.encryption

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Desc： 散列/哈希加密
 *
 *
 *
 * @author ： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/8/16 17:01
 * @version 1
 */
object SHAUtils {
    /**
     * 进行sha1加密
     *
     * @param val 加密的字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    @Throws(NoSuchAlgorithmException::class)
    fun getSHA(`val`: String): String {
        val md5: MessageDigest = MessageDigest.getInstance("SHA-1")
        md5.update(`val`.toByteArray())
        val m: ByteArray = md5.digest() //加密
        return byte2hex(m)
    }

    private fun byte2hex(b: ByteArray): String {
        var hs: String = ""
        var stmp: String = ""
        for (n in b.indices) {
            stmp = (Integer.toHexString(b.get(n).toInt() and 0XFF))
            if (stmp.length == 1) {
                hs = hs + "0" + stmp
            } else {
                hs = hs + stmp
            }
        }
        return hs
    }
}
